package com.liuya.safe.policy.controller;

import com.liuya.base.BaseController;
import com.liuya.common.WebUtil;
import com.liuya.safe.model.SafeBusinessData;
import com.liuya.safe.policy.service.BusinessDataManagerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 业务数据策略测试
 */
@Controller
@Api(value = "查询策略", description = "查询策略")
@RequestMapping(value = "busiDataPolicy")
public class BusinessDataPolicyController extends BaseController{
    private static final Log log = LogFactory.getLog(BusinessDataPolicyController.class);

    @Autowired
    @Qualifier("businessDataManagerService")
    private BusinessDataManagerService service;

    @ApiOperation(value = "编辑查询策略")
//    @RequiresPermissions("sys.busiDataPolicy.policy")
    @RequestMapping(value = "/policy")
    public Object policy(HttpServletRequest req, HttpServletResponse rep, ModelMap modelMap){
        String oper = req.getParameter("oper");
        String id = WebUtil.getStringParameter(req, "id", "0");
        String url = policy(oper, id);
        return url;
    }

    protected String policy(String oper, String id){
        if ("testPolicy".equals(oper)) {
            return "redirect:/busiDataPolicyTest/testPolicy.do?oper=loadFresh&id=" + id;
        } else {
            // edit policy
            boolean rawScript = isRawScript(id);
            if (rawScript) {
                return "redirect:/busiDataPolicyRaw/editPolicy?oper=loadFresh&id=" + id;
            } else {
                return "redirect:/busiDataPolicyDesign/editPolicy?oper=loadFresh&id=" + id;
            }
        }
    }

    public boolean isRawScript(String id) {
        SafeBusinessData uc = service.getBusinessData(id);

        com.liuya.db.script.BusinessData script = uc.getScriptBusinessData();
        return script.isRawScript();
    }
}
